package com.example.ctrip.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * @description: 获取客户端请求参数中所有的信息
 * @author: zcy
 * @create: 2020-11-17
 **/
public class RequestUtils {

    /**
     * 获取客户端请求参数中所有的信息
     *
     * @param request
     * @return
     */
    public static MultiValueMap<String, String> getAllRequestParamMultiValueMap(final HttpServletRequest request) {
        MultiValueMap<String, String> res = new LinkedMultiValueMap<>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, Collections.singletonList(value));
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    public static Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }

    /**
     * JSONObject格式化为String;
     *
     * @param ret JSONObject
     * @return
     */
    public static String retString(JSONObject ret) {
        String jsonStr = "";
        jsonStr = JSON.toJSONString(ret);
        return jsonStr;
    }

}
